// 虚拟收藏功能管理
class MockFavoritesManager {
  constructor() {
    this.favorites = []
    this.init()
  }
  
  // 初始化，从本地存储加载收藏
  init() {
    try {
      const stored = uni.getStorageSync('mock_favorites')
      if (stored) {
        this.favorites = JSON.parse(stored)
      }
    } catch (error) {
      console.error('加载收藏失败:', error)
      this.favorites = []
    }
  }
  
  // 保存到本地存储
  save() {
    try {
      uni.setStorageSync('mock_favorites', JSON.stringify(this.favorites))
    } catch (error) {
      console.error('保存收藏失败:', error)
    }
  }
  
  // 获取用户收藏列表
  getUserFavorites(userId) {
    return this.favorites.filter(fav => fav.userId === userId)
  }
  
  // 添加收藏
  addFavorite(userId, songInfo) {
    const favorite = {
      id: Date.now(),
      userId: userId,
      songId: songInfo.id,
      songTitle: songInfo.name,
      artist: songInfo.artist,
      album: songInfo.album || '',
      coverUrl: songInfo.cover,
      addTime: new Date().toISOString()
    }
    
    // 检查是否已收藏
    const existing = this.favorites.find(fav => 
      fav.userId === userId && fav.songId === songInfo.id
    )
    
    if (existing) {
      throw new Error('歌曲已收藏')
    }
    
    this.favorites.push(favorite)
    this.save()
    return favorite
  }
  
  // 取消收藏
  removeFavorite(userId, songId) {
    const index = this.favorites.findIndex(fav => 
      fav.userId === userId && fav.songId === songId
    )
    
    if (index === -1) {
      throw new Error('收藏记录不存在')
    }
    
    this.favorites.splice(index, 1)
    this.save()
    return true
  }
  
  // 检查是否已收藏
  isFavorite(userId, songId) {
    return this.favorites.some(fav => 
      fav.userId === userId && fav.songId === songId
    )
  }
  
  // 获取收藏数量
  getFavoriteCount(userId) {
    return this.getUserFavorites(userId).length
  }
}

// 创建单例实例
const mockFavoritesManager = new MockFavoritesManager()

export default mockFavoritesManager

